//
//  AddChengzhangViewController.m
//  XRSquare
//
//  Created by UaenaMo on 2018/8/8.
//  Copyright © 2018年 UaenaMo. All rights reserved.
//

#import "AddChengzhangViewController.h"
#import "PGDatePickManager.h"
#import <Qiniu/QiniuSDK.h>
#import "ImageCollectionViewCell.h"

static NSString * identifer = @"cell";

@interface AddChengzhangViewController ()<UINavigationControllerDelegate,UIImagePickerControllerDelegate,PGDatePickerDelegate,UICollectionViewDelegate,UICollectionViewDataSource,ImageSelectionDelegate,UIScrollViewDelegate>
{
    UIScrollView * contentScorllView;
    
    UILabel * titleLabel;
    UITextField * titleTextField;
    UILabel * timeLabel;
    UILabel * timeContent;
    UILabel * descriptionLabel;
    GCPlaceholderTextView * descriptionContennt;
    
    UILabel * imageLabel;
    UICollectionView * imageContentView;
    UIButton * addImageButton;
    
    UILabel * typeLabel;
    UILabel * typeContent;
    UILabel * ruleLabel;
    UILabel * ruleSource;
    
    NSMutableArray * imageArr;
    
    NSString * type;
    NSString * showType;
    NSString * time;
}
@end

@implementation AddChengzhangViewController

-(instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])
    {
        imageArr = [NSMutableArray array];
    }
    return self;
}

-(void)backAction
{
    [self.navigationController popViewControllerAnimated:YES];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    UIBarButtonItem * rightItem = [[UIBarButtonItem alloc]initWithTitle:@"发布" style:UIBarButtonItemStylePlain target:self action:@selector(okAction)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.navigationController.navigationBar.tintColor = [UIColor grayColor];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithImage:[[UIImage imageNamed:@"back"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate] style:UIBarButtonItemStylePlain target:self action:@selector(backAction)];
    
    if (self.type == 1)
    {
        self.navigationItem.title = @"个人大事记";
    }
    if (self.type == 2)
    {
        self.navigationItem.title = @"个人采风";
    }
    if (self.type == 3)
    {
        self.navigationItem.title = @"校园活动";
    }
    if (self.type == 4)
    {
        self.navigationItem.title = @"社会活动";
    }
    if (self.type == 5)
    {
        self.navigationItem.title = @"技能资质";
    }
    if (self.type == 6)
    {
        self.navigationItem.title = @"梦想舞台";
    }
    
    CGRect rectStatus = [[UIApplication sharedApplication] statusBarFrame];
    CGRect rectNav = self.navigationController.navigationBar.frame;
    
    contentScorllView = [[UIScrollView alloc]initWithFrame:CGRectMake(0, rectStatus.size.height + rectNav.size.height, ScreenWidth, ScreenHeight - rectStatus.size.height - rectNav.size.height)];
    contentScorllView.delegate = self;
    [self.view addSubview:contentScorllView];
    
    titleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, ScreenWidth, 20)];
    titleLabel.font = [UIFont systemFontOfSize:15];
    titleLabel.text = @"标题";
    [contentScorllView addSubview:titleLabel];
    
    titleTextField = [[UITextField alloc]initWithFrame:CGRectMake(10, 40, ScreenWidth, 20)];
    titleTextField.font = [UIFont systemFontOfSize:15];
    titleTextField.placeholder = @"请输入标题";
    [contentScorllView addSubview:titleTextField];
    
    {
        UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, 70, ScreenWidth, 1)];
        line.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
        [contentScorllView addSubview:line];
    }
    
    timeLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 80, ScreenWidth, 20)];
    timeLabel.font = [UIFont systemFontOfSize:15];
    timeLabel.text = @"事件时间";
    [contentScorllView addSubview:timeLabel];

    timeContent = [[UILabel alloc]initWithFrame:CGRectMake(10, 110, ScreenWidth, 20)];
    timeContent.font = [UIFont systemFontOfSize:15];
    timeContent.text = @"请选取事件时间";
    timeContent.userInteractionEnabled = YES;
    timeContent.textColor = [UIColor colorFromHexCode:@"b3b3b3"];
    [contentScorllView addSubview:timeContent];
    UITapGestureRecognizer * tap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectTime)];
    [timeContent addGestureRecognizer:tap];
    
    {
        UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, 140, ScreenWidth, 1)];
        line.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
        [contentScorllView addSubview:line];
    }
    
    descriptionLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, 150, ScreenWidth, 20)];
    descriptionLabel.font = [UIFont systemFontOfSize:15];
    descriptionLabel.text = @"描述";
    [contentScorllView addSubview:descriptionLabel];
    
    descriptionContennt = [[GCPlaceholderTextView alloc]initWithFrame:CGRectMake(10, 180, ScreenWidth, 80)];
    descriptionContennt.placeholder = @"请输入描述";
    descriptionContennt.font = [UIFont systemFontOfSize:15];
    [contentScorllView addSubview:descriptionContennt];
    
    {
        UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, 270, ScreenWidth, 1)];
        line.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
        [contentScorllView addSubview:line];
    }
    
    CGFloat height = 280;
    
    if (self.type == 2 || self.type == 3 || self.type == 4 || self.type == 5)
    {
        imageLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, height, ScreenWidth, 20)];
        imageLabel.font = [UIFont systemFontOfSize:15];
        imageLabel.text = @"上传照片";
        [contentScorllView addSubview:imageLabel];
        
        height += 30;
        
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake(90, 90);
        layout.minimumLineSpacing = 0;
        layout.minimumInteritemSpacing = 0;
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        
        imageContentView = [[UICollectionView alloc]initWithFrame:CGRectMake(10, height, ScreenWidth - 20, 90) collectionViewLayout:layout];
        imageContentView.delegate = self;
        imageContentView.dataSource = self;
        imageContentView.backgroundColor = [UIColor whiteColor];
        [contentScorllView addSubview:imageContentView];
        
        [imageContentView registerClass:[ImageCollectionViewCell class] forCellWithReuseIdentifier:identifer];
        
        height += 100;
        
        {
            UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, height, ScreenWidth, 1)];
            line.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
            [contentScorllView addSubview:line];
        }
        
        height += 10;
    }
    
    typeLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, height, ScreenWidth, 20)];
    typeLabel.font = [UIFont systemFontOfSize:15];
    typeLabel.text = @"事件属性";
    [contentScorllView addSubview:typeLabel];
    
    height += 30;
    
    typeContent = [[UILabel alloc]initWithFrame:CGRectMake(10, height, ScreenWidth, 20)];
    typeContent.font = [UIFont systemFontOfSize:15];
    typeContent.text = @"请选择事件属性";
    typeContent.userInteractionEnabled = YES;
    typeContent.textColor = [UIColor colorFromHexCode:@"b3b3b3"];
    [contentScorllView addSubview:typeContent];
    UITapGestureRecognizer * tap1 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectType)];
    [typeContent addGestureRecognizer:tap1];
    
    height += 30;
    
    {
        UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, height, ScreenWidth, 1)];
        line.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
        [contentScorllView addSubview:line];
    }
    
    height += 10;
    
    ruleLabel = [[UILabel alloc]initWithFrame:CGRectMake(10, height, ScreenWidth, 20)];
    ruleLabel.font = [UIFont systemFontOfSize:15];
    ruleLabel.text = @"可见权限";
    [contentScorllView addSubview:ruleLabel];
    
    height += 30;
    
    ruleSource = [[UILabel alloc]initWithFrame:CGRectMake(10, height, ScreenWidth, 20)];
    ruleSource.font = [UIFont systemFontOfSize:15];
    ruleSource.text = @"请选择可见属性";
    ruleSource.userInteractionEnabled = YES;
    ruleSource.textColor = [UIColor colorFromHexCode:@"b3b3b3"];
    [contentScorllView addSubview:ruleSource];
    UITapGestureRecognizer * tap2 = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(selectShowType)];
    [ruleSource addGestureRecognizer:tap2];
    
    height += 30;
    
    {
        UIView * line = [[UIView alloc]initWithFrame:CGRectMake(0, height, ScreenWidth, 1)];
        line.backgroundColor = [UIColor colorFromHexCode:@"f3f3f3"];
        [contentScorllView addSubview:line];
    }
    
    height += 10;
    
    if (height < ScreenHeight)
    {
        contentScorllView.contentSize = CGSizeMake(ScreenWidth, ScreenHeight);
    }
    else
    {
        contentScorllView.contentSize = CGSizeMake(ScreenWidth, height);
    }
}

-(void)okAction
{

    [SVProgressHUD show];
    [NetRequestCenter personalarchiveWithType:[NSString stringWithFormat:@"%d",self.type - 1] eventime:time title:titleTextField.text content:descriptionContennt.text pic:imageArr showtype:showType property:type result:^(BOOL success, NSDictionary *resultDic) {
        if (success)
        {
            [SVProgressHUD showSuccessWithStatus:@"发布成功"];
            [self.navigationController popViewControllerAnimated:YES];
        }
        else
        {
            [SVProgressHUD showErrorWithStatus:[resultDic objectForKey:@"message"]];
        }
    }];
}

-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    [titleTextField resignFirstResponder];
    [descriptionContennt resignFirstResponder];
}

-(void)selectTime
{
    PGDatePickManager *datePickManager = [[PGDatePickManager alloc]init];
    datePickManager.isShadeBackgroud = true;
    PGDatePicker *datePicker = datePickManager.datePicker;
    datePicker.delegate = self;
    datePicker.tag = 1;
    datePicker.datePickerType = PGPickerViewType2;
    datePicker.datePickerMode = PGDatePickerModeDateHourMinute;
    [self presentViewController:datePickManager animated:false completion:nil];
    
    [datePicker setDate:[NSDate date] animated:NO];
}

#pragma PGDatePickerDelegate
- (void)datePicker:(PGDatePicker *)datePicker didSelectDate:(NSDateComponents *)dateComponents
{
    NSLog(@"dateComponents = %@", dateComponents);
    
    NSCalendar * calendar = [NSCalendar currentCalendar];
    NSDate * date = [calendar dateFromComponents:dateComponents];
    
    if (datePicker.tag == 1)
    {
        time = [NSString stringWithFormat:@"%ld-%02ld-%02ld %02ld:%02ld:%02ld",(long)dateComponents.year,(long)dateComponents.month,dateComponents.day,dateComponents.hour,dateComponents.minute,dateComponents.second];
        timeContent.text = time;
    }
}

-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if ([imageArr count] < 9)
    {
        return [imageArr count] + 1;
    }
    else
    {
        return [imageArr count];
    }
}

-(UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    ImageCollectionViewCell * cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifer forIndexPath:indexPath];
    if ([imageArr count] < 9)
    {
        if (indexPath.item == [imageArr count])
        {
            [cell loadData:nil];
        }
        else
        {
            [cell loadData:[imageArr objectAtIndex:indexPath.item]];
        }
    }
    else
    {
        [cell loadData:[imageArr objectAtIndex:indexPath.item]];
    }
    
    cell.delegate = self;
    return cell;
}

-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.item == [imageArr count])
    {
        if ([imageArr count] < 9)
        {
            [self addImageAction];
        }
    }
}

-(void)deleteImageIndex:(NSInteger)index
{
    [imageArr removeObjectAtIndex:index];
    [imageContentView reloadData];
}

-(void)addImageAction
{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * timeOrder = [UIAlertAction actionWithTitle:@"相机" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];
    UIAlertAction * collectionOrder = [UIAlertAction actionWithTitle:@"相册" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController * imagePicker = [[UIImagePickerController alloc]init];
        imagePicker.delegate = self;
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.allowsEditing = YES;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"Cancel Action");
    }];
    
    [alertController addAction:timeOrder];
    [alertController addAction:collectionOrder];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    UIImage * selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:picker completion:nil];

    [SVProgressHUD show];
    [NetRequestCenter uptokenwithbucket:@"0" result:^(BOOL success, NSDictionary *resultDic) {
        if (success)
        {
            NSString * token = [resultDic objectForKey:@"uptoken"];
            NSData * imageData = UIImageJPEGRepresentation(selectedImage, 0.5);
            QNUploadOption * option=[[QNUploadOption alloc] initWithProgressHandler:^(NSString *key, float percent) {
                NSLog(@"key=%@ ,percent=%f",key,percent);
            }];
            
            QNUploadManager * upload=[[QNUploadManager alloc] init];
            
            [upload putData:imageData key:[[token componentsSeparatedByString:@":"]firstObject] token:token complete:^(QNResponseInfo *info, NSString *key, NSDictionary *res) {
                NSLog(@"statusCode=%d",info.statusCode);
                NSLog(@"%@",res);
                
                if(info.statusCode==200)
                {
                    [imageArr addObject:[res objectForKey:@"hash"]];
                    [SVProgressHUD showSuccessWithStatus:@"上传成功"];
                    [imageContentView reloadData];
                }
                else
                {
                    [SVProgressHUD showErrorWithStatus:[info.error localizedDescription]];
                }
                
            } option:option];
        }
    }];
}

-(void)selectType
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * gern = [UIAlertAction actionWithTitle:@"个人" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        typeContent.text = @"个人";
        type = @"0";
    }];
    UIAlertAction * huoban = [UIAlertAction actionWithTitle:@"伙伴" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        typeContent.text = @"伙伴";
        type = @"1";
    }];
    UIAlertAction * jiating = [UIAlertAction actionWithTitle:@"家庭" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        typeContent.text = @"家庭";
        type = @"2";
    }];
    UIAlertAction * shiye = [UIAlertAction actionWithTitle:@"事业" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        typeContent.text = @"事业";
        type = @"3";
    }];

    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    
    [alertController addAction:gern];
    [alertController addAction:huoban];
    [alertController addAction:jiating];
    [alertController addAction:shiye];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

-(void)selectShowType
{
UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil
                                                                             message:nil
                                                                      preferredStyle:UIAlertControllerStyleActionSheet];
    
    UIAlertAction * quanbu = [UIAlertAction actionWithTitle:@"全部可见" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        ruleSource.text = @"全部可见";
        showType = @"0";
    }];
    UIAlertAction * ziji = [UIAlertAction actionWithTitle:@"仅自己可见" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        ruleSource.text = @"仅自己可见";
        showType = @"1";
    }];
    UIAlertAction * haohou = [UIAlertAction actionWithTitle:@"仅好友可见" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        ruleSource.text = @"仅好友可见";
        showType = @"2";
    }];
    UIAlertAction * cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    
    [alertController addAction:quanbu];
    [alertController addAction:ziji];
    [alertController addAction:haohou];
    [alertController addAction:cancelAction];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
